import logger from "../utils/logger";
import { dbName } from "./constant";
import { getDBReady } from "./dbReady";
/**
 * 添加日期记录
 * @param string 格式 YYYY-MM-DD 
 * @return.data 成功返回新增成功的dateid number | fail
 */
export async function addDateRecord(date : DB.Date['date']) : Promise<number | null> {
	if (!getDBReady()) return null;
	const queryId = await queryDateId(date);
	if (queryId) {
		return queryId;
	}
	return new Promise((resolve) => {
		const sql = `
	      INSERT INTO dates (date) 
	      VALUES ('${date}')`;

		plus.sqlite.executeSql({
			name: dbName,
			sql: [sql],
			success: async () => {
				logger('添加成功');
				resolve(await queryDateId(date));
			},
			fail: (e) => {
				logger('添加失败:', e.message);
				resolve(null);
			}
		});
	});
}
/**
 * 查询往期记录日期对应的id
 * @param string 格式 YYYY-MM-DD 可选值
 * @return dateId number | null
 */
export async function queryDateId(date : DB.Date['date']) {
	if (!getDBReady()) return null;
	return new Promise<number | null>((resolve) => {
		const sql = `SELECT * FROM dates WHERE date='${date}'`;

		plus.sqlite.selectSql({
			name: dbName,
			sql: sql,
			success: (res) => {
				logger('查询成功:', res);
				const dateId = res?.[0]?.dateId;
				resolve(dateId ?? null);
			},
			fail: (e) => {
				logger(e)
				resolve(null);
			}
		});
	});
}
/**
 * 查询往期日期记录列表
 * @return date数组
 */
export async function queryBatchDate() : Promise<Array<string>> {
	if (!getDBReady()) return null;
	return new Promise<string[] | null>((resolve) => {
		const sql = `SELECT * FROM dates`;

		plus.sqlite.selectSql({
			name: dbName,
			sql: sql,
			success: (res) => {
				logger('查询成功:', res);
				resolve(res);
			},
			fail: (e) => {
				logger(e)
				resolve(null);
			}
		});
	});
}
/**
 * 查询某时间段日期记录集
 * @param {{ startDate : string, endDate : string }} { startDate, endDate } startDate 开始时间 endDate 结束时间 
 * @return.data 日期记录集
 */
export async function batchDate({ startDate, endDate } : { startDate : string, endDate : string }) : Promise<Array<DB.DateSource>> {
	if (!getDBReady()) return null;
	return new Promise<DB.DateSource[] | null>((resolve) => {
		const sql = `SELECT * FROM dates WHERE date BETWEEN '${startDate}' AND '${endDate}'`;

		plus.sqlite.selectSql({
			name: dbName,
			sql: sql,
			success: (res) => {
				logger('查询成功:', res);
				resolve(res);
			},
			fail: (e) => {
				logger(e)
				resolve(null);
			}
		});
	});
}